package org.laptech.calculator.logic;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import org.laptech.calc.R;
import org.laptech.calculator.utils.DataBaseHelper;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;




/**
 * Класс описывающий калькулятор талантов
 *
 * @author Lapin R.
 */
public class TalentCalculator {
    private ArrayList<Integer> selectedTalents = new ArrayList<Integer>(7);
    private final int HERO_COUNT;
    private final Context context;
    ArrayList<Hero> heroes;

    public TalentCalculator(Context context) {


        HERO_COUNT = context.getResources().getInteger(R.integer.heroescount);
        //this.heroes = new ArrayList<Hero>(HERO_COUNT);
        this.heroes = new ArrayList<Hero>();
        this.context = context;
        for(int i=0;i<7;i++) {
            selectedTalents.add(0);
        }



    }

    /**
     * Получаем список героев из базы данных
     */
    public void selectHeroes()
    {
        if(heroes.isEmpty()) {
            DataBaseHelper dbhelper = new DataBaseHelper(context);
            try {
                dbhelper.createDataBase();
                dbhelper.openDataBase();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            SQLiteDatabase db = dbhelper.getReadableDatabase();
            try {
                Cursor cursor = db.rawQuery("SELECT * FROM heroes", null);
                for (boolean b = cursor.moveToFirst(); b; b = cursor.moveToNext()) {
                    Hero hero = new Hero();
                    hero.setName(cursor.getString(0));
                    hero.setGame(Game.valueOf(cursor.getString(1).toUpperCase()));
                    hero.setRole(Role.valueOf(cursor.getString(2).toUpperCase()));
                    hero.setCost(cursor.getInt(3));
                    heroes.add(hero);
                }

            } catch (Exception e) {
                Log.e("error", e.getMessage());
            }
            dbhelper.close();
        }


    }
    /**
     * Получаем список способностей и аттрибутов для текущего героя
     * @param i - номер героя в списке
     */
    public void initAbilitiesAndAttributes(int i)
    {
        if(i>=0 && i<heroes.size()) {

            DataBaseHelper dbhelper = new DataBaseHelper(context);
            try {
                dbhelper.createDataBase();
                dbhelper.openDataBase();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            SQLiteDatabase db = dbhelper.getReadableDatabase();
            if(heroes.get(i).getSpells()==null) {
                try {
                    Cursor cursor = db.rawQuery("SELECT * FROM heroabilities WHERE hero='" + heroes.get(i).getName() + "'", null);
                    ArrayList<Spell> spells = new ArrayList<>();
                    for (boolean b = cursor.moveToFirst(); b; b = cursor.moveToNext()) {
                        Spell spell = new Spell();
                        Cursor cursor1 = db.rawQuery("SELECT * FROM abilities WHERE name='" + cursor.getString(1) + "'", null);
                        if (cursor1.moveToFirst()) {
                            spell.setSpellID(cursor1.getString(0));
                            spell.setCooldown(cursor1.getInt(1));
                            if (cursor1.getString(2) != null)
                                spell.setHotkey(cursor1.getString(2).charAt(0));
                            spell.setRescost(cursor1.getInt(3));
                        }
                        int num = 0;// номер индекса параметра
                        ArrayList<Spell.Param> params = new ArrayList<>();
                        do {

                            cursor1 = db.rawQuery("SELECT * FROM abilityparams WHERE name='" + cursor.getString(1) + "' and ind=" + num, null);
                            if (cursor1.moveToFirst()) {
                                Spell.Param param = new Spell.Param();
                                param.val = cursor1.getDouble(1);
                                param.valplvl = cursor1.getDouble(2);
                                params.add(param);
                            } else break;
                            num++;
                        } while (true);
                        spell.setParams(params);
                        spells.add(spell);
                    }
                    heroes.get(i).setSpells(spells);
                } catch (Exception e) {
                    Log.e("error", e.getMessage());
                }
            }
            if(heroes.get(i).getAttributes()==null)
            {
                try {
                    Cursor cursor1 = db.rawQuery("SELECT * FROM attributes WHERE hero='" + heroes.get(i).getName() + "'", null);

                    if(cursor1.moveToFirst()){
                        Attributes attributes = new Attributes();

                            attributes.setHp(cursor1.getInt(1));
                            attributes.setHpplvl(cursor1.getInt(2));
                            attributes.setResource(ResourceType.valueOf(cursor1.getString(3).toUpperCase()));
                            attributes.setHpreg(cursor1.getDouble(6));
                            attributes.setHpregplvl(cursor1.getDouble(7));
                            if(attributes.getResource()!=ResourceType.NONE)
                            {
                                attributes.setRes(cursor1.getInt(4));
                                attributes.setResplvl(cursor1.getInt(5));
                                attributes.setResreg(cursor1.getDouble(8));
                                attributes.setResregplvl(cursor1.getDouble(9));
                            }
                            attributes.setAs(cursor1.getDouble(10));
                            attributes.setDmg(cursor1.getInt(11));
                            attributes.setDmgplvl(cursor1.getInt(12));
                            if(cursor1.getDouble(13)>0.00001)
                            {
                                attributes.setRange(cursor1.getDouble(13));
                            }








                        heroes.get(i).setAttributes(attributes);
                    }

                } catch (Exception e) {
                    Log.e("error", e.getMessage());
                }
            }
            dbhelper.close();
        }



    }
    public void setSelTalent(int tier, int value)
    {
        selectedTalents.set(tier-1,value);
    }

    public int getTierValue(int tier)
    {
        return selectedTalents.get(tier-1);
    }


    public Hero getHero(int i)
    {
        return heroes.get(i);
    }






    public int hCount() {
        return heroes.size();
    }
}
